package com.zhangzy.qm.util;
import javapns.back.PushNotificationManager;
import javapns.back.SSLConnectionHelper;
import javapns.data.Device;
import javapns.data.PayLoad;

import org.apache.log4j.Logger;


//Connect to APNs
/************************************************
测试的服务器地址：gateway.sandbox.push.apple.com /端口2195 
产品推送服务器地址：gateway.push.apple.com / 2195 
 ***************************************************/

public class ApnsSend {
	private static final Logger logger = Logger.getLogger("ulog");
	private static final  String host = "gateway.push.apple.com"; //正式：gateway.push.apple.com ,测试：gateway.sandbox.push.apple.com
	private static final  int port = 2195;
	private static final  String certificatePath = "D:/apnsCertify/free_movie.p12";//导出的证书
	private static final  String certificatePassword = "superjoo";//此处注意导出的证书密码不能为空因为空密码会报错
	
	/**
	 * 推送信息到APNS
	 * @Methods Name doSend
	 * @Create In Sep 15, 2012 By zhenyu
	 * @param deviceToken :用户token
	 * @param alertMessage：提示信息
	 * @param badge：显示数量
	 */
	public static void  doSend(String deviceToken,String alertMessage,int badge){
		try {
			logger.info("push message start");
			PayLoad payLoad = new PayLoad();
			payLoad.addAlert(alertMessage);//push的内容
			payLoad.addBadge(badge);//图标小红圈的数值
			payLoad.addSound("default");//铃音

			PushNotificationManager pushManager = PushNotificationManager.getInstance();
			pushManager.addDevice("iPhone", deviceToken);

			pushManager.initializeConnection(host, port, certificatePath,
					certificatePassword,
					SSLConnectionHelper.KEYSTORE_TYPE_PKCS12);

			//Send Push
			Device client = pushManager.getDevice("iPhone");
			pushManager.sendNotification(client, payLoad);
			pushManager.stopConnection();

			pushManager.removeDevice("iPhone");
			logger.info("push message end!!!");
		} catch (Exception e) {
			logger.error(" doSend: ",e);
		}
	}
	
	/**
	 * 单元测试
	 * @Methods Name main
	 * @Create In Sep 15, 2012 By musicbear
	 * @param args void
	 */
	public static void main(String[] args){
		String token = "e775b5892f3334427c14def8aa4d8189a4ec1c795020072f4baa7ee92e50b1db";
		doSend(token,"This is test message",1);
	}
}
